//! # 组件构建器实现
//! 
//! 本模块提供了针对微服务组件的构建器实现。

use crate::config::*;
use rustcloud_core::ServiceResult;

/// 注册中心配置构建器
pub struct RegistryConfigBuilder {
    config: RegistryConfig,
}

impl RegistryConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: RegistryConfig::default(),
        }
    }

    pub fn registry_type(mut self, registry_type: &str) -> Self {
        self.config.registry_type = registry_type.to_string();
        self
    }

    pub fn endpoints(mut self, endpoints: Vec<String>) -> Self {
        self.config.endpoints = endpoints;
        self
    }

    pub fn namespace(mut self, namespace: Option<String>) -> Self {
        self.config.namespace = namespace;
        self
    }

    pub fn group(mut self, group: Option<String>) -> Self {
        self.config.group = group;
        self
    }

    pub fn build(self) -> ServiceResult<RegistryConfig> {
        Ok(self.config)
    }
}

/// 负载均衡配置构建器
pub struct LoadBalancerConfigBuilder {
    config: LoadBalancerConfig,
}

impl LoadBalancerConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: LoadBalancerConfig::default(),
        }
    }

    pub fn strategy(mut self, strategy: &str) -> Self {
        self.config.strategy = strategy.to_string();
        self
    }

    pub fn weights(mut self, weights: std::collections::HashMap<String, u32>) -> Self {
        self.config.weights = weights;
        self
    }

    pub fn build(self) -> ServiceResult<LoadBalancerConfig> {
        Ok(self.config)
    }
}

/// 熔断器配置构建器
pub struct CircuitBreakerConfigBuilder {
    config: CircuitBreakerConfig,
}

impl CircuitBreakerConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: CircuitBreakerConfig::default(),
        }
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    pub fn failure_threshold(mut self, threshold: u32) -> Self {
        self.config.failure_threshold = threshold;
        self
    }

    pub fn success_threshold(mut self, threshold: u32) -> Self {
        self.config.success_threshold = threshold;
        self
    }

    pub fn timeout_ms(mut self, timeout_ms: u64) -> Self {
        self.config.timeout_ms = timeout_ms;
        self
    }

    pub fn max_concurrent_requests(mut self, max_requests: u32) -> Self {
        self.config.max_concurrent_requests = max_requests;
        self
    }

    pub fn request_volume_threshold(mut self, threshold: u32) -> Self {
        self.config.request_volume_threshold = threshold;
        self
    }

    pub fn error_percentage_threshold(mut self, threshold: f64) -> Self {
        self.config.error_percentage_threshold = threshold;
        self
    }

    pub fn sleep_window_ms(mut self, sleep_window_ms: u64) -> Self {
        self.config.sleep_window_ms = sleep_window_ms;
        self
    }

    pub fn build(self) -> ServiceResult<CircuitBreakerConfig> {
        Ok(self.config)
    }
}

/// 监控配置构建器
pub struct MonitoringConfigBuilder {
    config: MonitoringConfig,
}

impl MonitoringConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: MonitoringConfig::default(),
        }
    }

    pub fn metrics<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(MetricsConfigBuilder) -> MetricsConfigBuilder,
    {
        let builder = MetricsConfigBuilder::new();
        self.config.metrics = configure(builder).build().unwrap_or_default();
        self
    }

    pub fn tracing<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(TracingConfigBuilder) -> TracingConfigBuilder,
    {
        let builder = TracingConfigBuilder::new();
        self.config.tracing = configure(builder).build().unwrap_or_default();
        self
    }

    pub fn logging<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(LoggingConfigBuilder) -> LoggingConfigBuilder,
    {
        let builder = LoggingConfigBuilder::new();
        self.config.logging = configure(builder).build().unwrap_or_default();
        self
    }

    pub fn health_check<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(HealthCheckConfigBuilder) -> HealthCheckConfigBuilder,
    {
        let builder = HealthCheckConfigBuilder::new();
        self.config.health_check = configure(builder).build().unwrap_or_default();
        self
    }

    pub fn build(self) -> ServiceResult<MonitoringConfig> {
        Ok(self.config)
    }
}

/// 指标配置构建器
pub struct MetricsConfigBuilder {
    config: MetricsConfig,
}

impl MetricsConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: MetricsConfig::default(),
        }
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    pub fn port(mut self, port: u16) -> Self {
        self.config.port = port;
        self
    }

    pub fn path(mut self, path: &str) -> Self {
        self.config.path = path.to_string();
        self
    }

    pub fn prometheus<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(PrometheusConfigBuilder) -> PrometheusConfigBuilder,
    {
        let builder = PrometheusConfigBuilder::new();
        self.config.prometheus = configure(builder).build().unwrap_or_default();
        self
    }

    pub fn build(self) -> ServiceResult<MetricsConfig> {
        Ok(self.config)
    }
}

/// Prometheus配置构建器
pub struct PrometheusConfigBuilder {
    config: PrometheusConfig,
}

impl PrometheusConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: PrometheusConfig::default(),
        }
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    pub fn scrape_interval_seconds(mut self, interval: u64) -> Self {
        self.config.scrape_interval_seconds = interval;
        self
    }

    pub fn label(mut self, key: &str, value: &str) -> Self {
        self.config.labels.insert(key.to_string(), value.to_string());
        self
    }

    pub fn build(self) -> ServiceResult<PrometheusConfig> {
        Ok(self.config)
    }
}

/// 追踪配置构建器
pub struct TracingConfigBuilder {
    config: TracingConfig,
}

impl TracingConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: TracingConfig::default(),
        }
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    pub fn sampling_rate(mut self, rate: f64) -> Self {
        self.config.sampling_rate = rate;
        self
    }

    pub fn jaeger<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(JaegerConfigBuilder) -> JaegerConfigBuilder,
    {
        let builder = JaegerConfigBuilder::new();
        self.config.jaeger = Some(configure(builder).build().unwrap_or_default());
        self
    }

    pub fn batch<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(BatchConfigBuilder) -> BatchConfigBuilder,
    {
        let builder = BatchConfigBuilder::new();
        self.config.batch = configure(builder).build().unwrap_or_default();
        self
    }

    pub fn build(self) -> ServiceResult<TracingConfig> {
        Ok(self.config)
    }
}

/// Jaeger配置构建器
pub struct JaegerConfigBuilder {
    config: JaegerConfig,
}

impl JaegerConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: JaegerConfig {
                agent_endpoint: "localhost:6831".to_string(),
                service_name: "rustcloud-service".to_string(),
            },
        }
    }

    pub fn agent_endpoint(mut self, endpoint: &str) -> Self {
        self.config.agent_endpoint = endpoint.to_string();
        self
    }

    pub fn service_name(mut self, name: &str) -> Self {
        self.config.service_name = name.to_string();
        self
    }

    pub fn build(self) -> ServiceResult<JaegerConfig> {
        Ok(self.config)
    }
}

/// 批处理配置构建器
pub struct BatchConfigBuilder {
    config: BatchConfig,
}

impl BatchConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: BatchConfig::default(),
        }
    }

    pub fn batch_size(mut self, size: usize) -> Self {
        self.config.batch_size = size;
        self
    }

    pub fn timeout_ms(mut self, timeout_ms: u64) -> Self {
        self.config.timeout_ms = timeout_ms;
        self
    }

    pub fn build(self) -> ServiceResult<BatchConfig> {
        Ok(self.config)
    }
}

/// 日志配置构建器
pub struct LoggingConfigBuilder {
    config: LoggingConfig,
}

impl LoggingConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: LoggingConfig::default(),
        }
    }

    pub fn level(mut self, level: &str) -> Self {
        self.config.level = level.to_string();
        self
    }

    pub fn format(mut self, format: &str) -> Self {
        self.config.format = format.to_string();
        self
    }

    pub fn output(mut self, output: LogOutputConfig) -> Self {
        self.config.output.push(output);
        self
    }

    pub fn structured<F>(mut self, configure: F) -> Self 
    where
        F: FnOnce(StructuredLogConfigBuilder) -> StructuredLogConfigBuilder,
    {
        let builder = StructuredLogConfigBuilder::new();
        self.config.structured = configure(builder).build().unwrap_or_default();
        self
    }

    pub fn build(self) -> ServiceResult<LoggingConfig> {
        Ok(self.config)
    }
}

/// 结构化日志配置构建器
pub struct StructuredLogConfigBuilder {
    config: StructuredLogConfig,
}

impl StructuredLogConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: StructuredLogConfig::default(),
        }
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    pub fn buffer_size(mut self, size: usize) -> Self {
        self.config.buffer_size = size;
        self
    }

    pub fn flush_interval_ms(mut self, interval_ms: u64) -> Self {
        self.config.flush_interval_ms = interval_ms;
        self
    }

    pub fn build(self) -> ServiceResult<StructuredLogConfig> {
        Ok(self.config)
    }
}

/// 健康检查配置构建器
pub struct HealthCheckConfigBuilder {
    config: HealthCheckConfig,
}

impl HealthCheckConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: HealthCheckConfig::default(),
        }
    }

    pub fn enabled(mut self, enabled: bool) -> Self {
        self.config.enabled = enabled;
        self
    }

    pub fn interval_seconds(mut self, interval: u64) -> Self {
        self.config.interval_seconds = interval;
        self
    }

    pub fn timeout_seconds(mut self, timeout: u64) -> Self {
        self.config.timeout_seconds = timeout;
        self
    }

    pub fn path(mut self, path: &str) -> Self {
        self.config.path = path.to_string();
        self
    }

    pub fn check_type(mut self, check_type: &str) -> Self {
        self.config.check_type = check_type.to_string();
        self
    }

    pub fn build(self) -> ServiceResult<HealthCheckConfig> {
        Ok(self.config)
    }
}